<template>
  <div id="wrapper" v-loading="loading">
    <div class="center-flex" v-if="page==='regist'">
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item label="">
          <el-input v-model="activeCode" placeholder="请输入激活码"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="activeSoft">激活</el-button>
          <el-link :underline="false" @click="deviceInfo" style="margin-left: 10px;">硬件信息</el-link>
        </el-form-item>
      </el-form>
    </div>
    <el-row :gutter="14" v-if="page==='index'">
      <el-col :span="6">
        <el-card class="box-card">
          <el-image style="width: 100%;height: 160px;" :src="certData.certPhoto">
            <div slot="error" class="image-slot"></div>
          </el-image>
          <div style="text-align: center;color: #C0C4CC;">
            <span @dblclick="opDev()">头像</span>
          </div>
        </el-card>
        <el-card shadow="never" class="images-card" style="margin-top: 10px;">
          <div style="height: 400px;margin-top: 5px;">
            <div v-if="imageCheckCount>0" style="height: 25px;padding: 0 10px 0px 25px;">
              <i class="el-icon-delete icon-btn" @click="delImages"></i>
            </div>
            <div class="image-container" :style="{height: imageCheckCount>0?'375px': '400px'}">
              <div style="display: flex;flex-direction: row;margin: 0 5px 5px;" v-for="item in certData.certImages">
                <el-checkbox v-model="item.checked" style="width: 20px;" @change="checkCertImage(item)"></el-checkbox>
                <el-image style="flex: 1;min-height: 100px;" :src="item.filePath" :preview-src-list="[item.filePath]">
                  <div slot="error" class="image-slot"></div>
                </el-image>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="11">
        <el-card class="box-card main-block" style="height: 100%;">
          <el-form ref="form" size="mini" :model="certData" label-width="80px">
            <el-row>
              <el-col :span="12">
                <el-form-item label="证件号码">
                  <el-input v-model="certData.certNo"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="有效日期">
                  <el-input v-model="certData.expireDate"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="英文姓">
                  <el-input v-model="certData.zhLastName"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="英文名">
                  <el-input v-model="certData.zhFirstName"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-form-item label="英文姓名">
                <el-input v-model="certData.zhName"></el-input>
              </el-form-item>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="性别">
                  <el-input v-model="certData.gender"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="出生日期">
                  <el-input v-model="certData.birthday"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="国籍">
                  <el-input v-model="certData.nationality"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
              </el-col>
            </el-row>
            <el-row>
              <el-form-item label="MRZ1">
                <el-input type="textarea" :rows="2" v-model="certData.mrz1"></el-input>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="MRZ2">
                <el-input type="textarea" :rows="2" v-model="certData.mrz2"></el-input>
              </el-form-item>
            </el-row>
          </el-form>
        </el-card>
        <el-image style="width: 100%;height: 320px;padding-top: 10px;" :src="vedioUrl">
          <div slot="error" class="image-slot">
            <i class="el-icon-picture-outline"></i>
          </div>
        </el-image>
      </el-col>
      <el-col :span="7">
        <el-card class="box-card">
          <el-card shadow="never" class="config-cls">
            <div style="padding: 5px 0;">选项</div>
            <!--<div>
              <el-checkbox v-model="autoCheckCert">自动侦测证件A</el-checkbox>
            </div>
            <div>
              <el-checkbox v-model="autoCheckCert">身份证自动侦测 I</el-checkbox>
            </div>
            <div>
              <el-checkbox v-model="autoCheckCert">图像平滑处理</el-checkbox>
            </div>
            <div>
              <el-checkbox v-model="autoCheckCert">开启紫光</el-checkbox>
            </div>-->
            <div>
              <!--<el-checkbox v-model="cutEdge">裁切边缘</el-checkbox>-->
              裁切边缘
              <el-input type="number" size="mini" v-model="cutEdgeVal"></el-input>
            </div>
            <div>
              <el-checkbox v-model="checkEdge" @change="openCheckEdge">纠偏裁边</el-checkbox>
            </div>
          </el-card>
          <el-row :gutter="5" class="btn-block">
            <el-col :span="12">
              <el-button style="width: 100%;" v-on:click="initDev">初始化</el-button>
            </el-col>
            <el-col :span="12">
              <!--<el-button style="width: 100%;" @click="start">开始</el-button>-->
              <el-button style="width: 100%;" @click="saveImage">保存图片</el-button>
            </el-col>
          </el-row>
          <el-row :gutter="5" class="btn-block">
            <el-col :span="12">
              <el-button style="width: 100%;" @click="readCert">手动读取证件</el-button>
            </el-col>
            <el-col :span="12">
              <el-button style="width: 100%;" @click="readElecCert">读取电子护照</el-button>
            </el-col>
          </el-row>
          <el-row :gutter="5" class="btn-block">
            <el-col :span="12">
              <el-button style="width: 100%;" @click="takePhoto">手动拍照</el-button>
            </el-col>
            <el-col :span="12">
              <el-button style="width: 100%;" :class="autoPhoto?'btn-select':''" @click="autoTakePhoto">自动拍照</el-button>
            </el-col>
          </el-row>
          <el-row :gutter="5" class="btn-block">
            <el-col :span="12">
              <el-radio v-model="vedioIndex" label="0" style="width: 100%;" border>主摄像头</el-radio>
            </el-col>
            <el-col :span="12">
              <el-radio v-model="vedioIndex" label="1" style="width: 100%;" border>副摄像头</el-radio>
            </el-col>
          </el-row>
          <div style="padding-top: 5px;">
            <el-button style="width: 100%;" @click="rotation90">摄像头旋转90°</el-button>
          </div>
          <div style="padding-top: 5px;">
            <el-button style="width: 100%;" @click="reconnectDevice">重连设备</el-button>
          </div>
          <div style="padding-top: 5px;">
            <el-button style="width: 100%;" v-on:click="exist()">退出</el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-dialog title="电脑信息" size="mini" :visible.sync="showDeviceInfo">
      <el-descriptions title="本机信息" :column="1" border>
        <el-descriptions-item label="主机名">
          <span v-text="machineInfo.hostname"></span>
        </el-descriptions-item>
        <el-descriptions-item label="操作系统">
          <span v-text="machineInfo.platform"></span>
        </el-descriptions-item>
        <el-descriptions-item label="MAC地址">
          <span v-text="machineInfo.mac"></span>
        </el-descriptions-item>
        <el-descriptions-item label="cpu架构">
          <span v-text="machineInfo.arch"></span>
        </el-descriptions-item>
        <el-descriptions-item label="cpu字节序">
          <span v-text="machineInfo.endianness"></span>
        </el-descriptions-item>
        <el-descriptions-item label="cpu序列号">
          <span v-text="machineInfo.cpuSerial"></span>
        </el-descriptions-item>
        <el-descriptions-item label="硬盘序列号">
          <span v-text="machineInfo.diskSerial"></span>
        </el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="showDeviceInfo = false">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import EnumUtil from "../utils/EnumUtil"
  import FileUtil from "../utils/FileUtil"
  import RegexUtil from "../utils/RegexUtil"
  import EloamInterface from "../utils/EloamInterface";
  import axios from 'axios'
  import DateUtil from "../utils/DateUtil";
  import WebSocketUtil from "../utils/WebSocketUtil";
  import FileSystem from "../utils/FileSystem";
  import CommonUtil from "../utils/CommonUtil";
  import ActiveSoftUtil from "../utils/ActiveSoftUtil";
  import SystemConfig from "../utils/SystemConfig";

  /*const tencentcloud = require("tencentcloud-sdk-nodejs-ocr")
  const OcrClient = tencentcloud.ocr.v20181119.Client

  const BaiduOcrClient = require("baidu-aip-sdk").ocr
  const baiduHttpClient = require("baidu-aip-sdk").HttpClient*/

  const { remote, ipcRenderer } = require("electron")
  const dialog = remote.dialog

  export default {
    name: 'landing-page',
    components: {},
    data () {
      return {
        certData: {
          //头像
          certPhoto: '',
          //图片
          certImages: [],
          //certImage: '',
          type: '',
          certNo: '',
          chName: '',
          zhFirstName: '',
          zhLastName: '',
          zhName: '',
          gender: '',
          birthday: '',
          //出生地
          birthPlace: '',
          //国家
          conuntry: '',
          //国籍
          nationality: '',
          expireDate: '',
          //签发地
          signPlace: '',
          //签发机关
          signOrg: '',
          //签发日期
          signDate: '',
          //持证人签名
          signature: '',
          mrz1: '',
          mrz2: ''
        },
        opData: {
          type: 'passport'
        },
        //baidu,tencent,umi,eloam
        ocrType: 'umi',
        loading: false,
        worker: null,
        tencentOcrClient: null,
        baiduOcrClient: null,
        //自动侦测证件
        autoCheckCert: false,
        //拍照纠偏
        cutEdge: false,
        cutEdgeVal: '',
        //纠偏裁边
        checkEdge: false,
        lightSource: 'white',
        selOrcTypeVisiable: false,
        autoPhoto: false,
        //分辨率
        zoominout: 0,
        //0-主摄像头，1-副摄像头
        vedioIndex: '0',
        //主摄像头：http://127.0.0.1:38088/video=stream&camidx=0
        //副摄像头：http://127.0.0.1:38088/video=stream&camidx=1
        prefixVedioUrl: 'http://127.0.0.1:38088/video=stream&camidx=',
        vedioUrl: 'http://127.0.0.1:38088/video=stream&camidx=0',
        //分辨率
        resolutions: [],
        imageShow: false,
        imageIndex: 0,
        baseFilePath: 'D:\\cert\\',
        imagePath: '',
        //读写器
        reader: {
          //操作类型，0：写RFID芯片，1：读RFID芯片，2：读身份证，3：读出入境证件
          cmd: 3,
          //入境证件MRZ
          mrz: ''
        },
        checked: false,
        imageCheckCount: 0,
        //index regist
        page: '',
        activeCode: '',
        showDeviceInfo: false,
        machineInfo: {}
      }
    },
    watch: {
      vedioIndex(newVal, oldVal){
        this.vedioUrl = this.prefixVedioUrl + newVal
      }
    },
    mounted() {
      this.init()
    },
    methods: {
      init(){
        this.loading = true
        /*try {
          //腾讯云初始化
          const clientConfig = {
            credential: {
              secretId: "AKIDhebTJ7sbCh8UhzOuYGpMm05EWp7JM6jA",
              secretKey: "PBmBQUi1EI9lZFj2DD5lJgSK3opeLuMu",
            },
            region: "ap-beijing",
            profile: {
              httpProfile: {
                endpoint: "ocr.tencentcloudapi.com",
              }
            }
          }
          // 实例化要请求产品的client对象,clientProfile是可选的
          this.tencentOcrClient = new OcrClient(clientConfig)

          //百度云初始化
          var APP_ID = "49935499"
          var API_KEY = "R1kz2YVkf8n6C7eoZbb4mz0X"
          var SECRET_KEY = "iNf5B4cVf3GelLstqueW1DYgqjSizx7R"
          this.baiduOcrClient = new BaiduOcrClient(APP_ID, API_KEY, SECRET_KEY)
          //设置request库的一些参数，例如代理服务地址，超时时间等
          baiduHttpClient.setRequestOptions({timeout: 5000})
          console.log(this.baiduOcrClient)
        }catch (e) {
          console.log('system error', e)
        }*/
        //查询本地激活码
        const avtiveCode = ActiveSoftUtil.getAvtiveCode()
        console.log('激活码', avtiveCode)
        const registCode = CommonUtil.createRegistCode()
        const md5RegistCode = CommonUtil.md5(registCode)
        console.log('注册码', md5RegistCode)
        if(avtiveCode===md5RegistCode){
          console.log('软件已激活')
          this.page = 'index'
          this.baseFilePath = SystemConfig.getSystemConfigType('baseImgPath') || 'D:\\cert\\'
          console.log('this.baseFilePath', this.baseFilePath)
          WebSocketUtil.initClient()
        }else {
          console.log('软件未激活')
          this.page = 'regist'
        }
        this.loading = false
      },
      activeSoft(){
        var registCode = CommonUtil.createRegistCode()
        console.log(registCode, this.activeCode)
        if(registCode === this.activeCode){
          //保存激活码
          ActiveSoftUtil.saveActiveCode(CommonUtil.md5(registCode))
          this.$message({
            message: '激活成功',
            type: 'success'
          })
          const thiz = this
          this.loading = true
          setTimeout(function () {
            thiz.page = 'index'
            thiz.loading = false
            WebSocketUtil.initClient()
          }, 500)
        }else{
          this.$message.error('激活码错误')
        }
      },
      initDev(){
        this.resetCertData()
        var url = this.prefixVedioUrl + this.vedioIndex + "&t="+DateUtil.getTimestamp()
        this.vedioUrl = url
        console.log('vedioUrl',this.vedioIndex,this.vedioUrl)
      },
      resetCertData(){
        this.certData = {
          certImages: [],
          type: '',
          certNo: '',
          chName: '',
          //英文名
          zhFirstName: '',
          //英文姓
          zhLastName: '',
          zhName: '',
          gender: '',
          birthday: '',
          //出生地
          birthPlace: '',
          //国家
          conuntry: '',
          //国籍
          nationality: '',
          expireDate: '',
          //签发地
          signPlace: '',
          //签发机关
          signOrg: '',
          //签发日期
          signDate: '',
          //持证人签名
          signature: '',
          mrz1: '',
          mrz2: ''
        }
        this.imageCheckCount = 0
      },
      readCert () {
        var thiz = this
        //console.log(RegexUtil.matchMRZ1('PSCHNYANG<<ZHAO<<<<<<<<<<<<<<<<<<<<<<<<<<<<<','CHN'))
        //console.log(RegexUtil.matchMRZ1('P<CHNLI<<OI<KWAN<<<<<<<<<<<<<<<<<<<<<<<<<<<<','CHN'))
        //this.parseEloamMrz('P<CHNLI<<OI<KWAN<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n' +
        //        'H912373880CHN9109098M3310182<G1111115<<<<<52')
        //console.log(RegexUtil.matchMRZ1('P<BLRFOFANOV<<LUKA<<<<<<<<<<<<<<<<<<<<<<<<<<', 'BLR'))
        //this.parseEloamMrz('P<BLRFOFANOV<<LUKA<<<<<<<<<<<<<<<<<<<<<<<<<<\n' +
        //        'XX12340433BLR8101246M24032146903869753530242')
        this.getCertImgByEloam()
        //this.readCertByReader("E006666693CHN8105185M2206194MDKLLELKNDMCA932")
      },
      readLocalCert () {
        dialog.showOpenDialog({
          //对话框标题
          title:'请选择图片',
          //设置选择的文件名称
          //defaultPath:'1.jpg',
          //过滤文件类型
          filters:[
            { name: 'Images', extensions: ['jpg', 'png'] }
          ]
        }).then(result=>{
          //图片选中后将回调此方法
          //返回的是一个对象
          console.log(result)
          thiz.resetCertData()
          thiz.parseCert(result.filePaths[0])
        }).catch(err=>{
          //异常处理
          console.log(err)
        })
      },
      parseCert(file){
        if (this.ocrType == 'tencent') {
          this.readCertByTencent(file)
        }else if(this.ocrType == 'baidu'){
          this.readCertByBaidu(file)
        }else if(this.ocrType == 'umi'){
          this.readCertByUmi(file)
        }
      },
      getImageFilePathOnly(){
        if(!this.imagePath){
          this.imagePath = DateUtil.getTimestamp() + '\\'
        }
        var path = this.baseFilePath + this.imagePath
        //创建目录
        FileSystem.makeDirectorySync(path)
        return path
      },
      getImageFilePath(name){
        var fileName =  DateUtil.getTimestamp()+ '.jpg'
        if(name){
          fileName = name
        }
        var path = this.getImageFilePathOnly()
        return path + fileName
      },
      getCertImgByEloam(){
        /*var file = 'C:\\Users\\lipanfeng\\Desktop\\shibie\\20250401202002.jpg'
        var params = {
          //OCR识别图片来源 0:从主头拍照 1:从路径导入 2:图片base64
          ocrflag: '1',
          //要识别的图片绝对路径或者baes64,用逗号分开
          imagelist: file,
          // 支持PDF，docx, xlsx，TXT
          savefilepath: 'D:\\cert\\ocr.txt'
        }
        EloamInterface.ocr(params, function (succ, data) {
          console.log('ocr', succ, data)
          this.loading = false
          if(!succ){
            this.$message.error(data || '照片不清晰，请重新拍照识别')
            return
          }
          //解析护照内容
          this.parseEloamMrz(data)
        }, this)
        return*/
        this.loading = true
        var config = {
          filepath: this.getImageFilePath()
        }
        EloamInterface.view1_scan(config, function (succ, file) {
          if(!succ){
            this.loading = false
            this.$message({
              message: '请检查摄像头是否打开',
              type: 'warning'
            })
            return
          }
          console.log("读取高拍仪文件", file)
          this.certData.certImages = [{filePath: file, checked: false}]
          var params = {
            //OCR识别图片来源 0:从主头拍照 1:从路径导入 2:图片base64
            ocrflag: '1',
            //要识别的图片绝对路径或者baes64,用逗号分开
            imagelist: file,
            // 支持PDF，docx, xlsx，TXT
            savefilepath: 'D:\\cert\\ocr.txt'
          }
          EloamInterface.ocr(params, function (succ, data) {
            console.log('ocr', succ, data)
            this.loading = false
            if(!succ){
              this.$message.error(data || '照片不清晰，请重新拍照识别')
              return
            }
            //解析护照内容
            this.parseEloamMrz(data)
          }, this)
        }, this)
      },
      parseEloamMrz(text){
        //先识别mrz2
        var mrz2List = RegexUtil.matchMRZ2(text)
        console.log(mrz2List)
        if(mrz2List && mrz2List.length==0){
          this.$message.error('照片不清晰，请重新拍照识别')
          return
        }
        var mrz2 = mrz2List[0]
        this.certData.mrz2 = mrz2
        var date = new Date();
        var yearNum = parseInt((date.getFullYear()+'').substring(2,4))
        console.log('yearNum', yearNum)
        //提取护照号码
        var passportNum = mrz2.substring(0,9)
        this.certData.certNo = passportNum
        //提取持证人生日
        var birthDate = ''
        if(parseInt(mrz2.substring(13, 15))>yearNum){
          birthDate = '19' + mrz2.substring(13, 19)
        }else{
          birthDate = '20' + mrz2.substring(13, 19)
        }
        this.certData.birthday = birthDate
        console.log('birthDate', birthDate, yearNum)
        //提取持证人性别
        var gender = mrz2.substring(20,21)
        this.certData.gender = EnumUtil.getGender(gender)
        //提取护照有效截止期
        var validUtilDate = '20' + mrz2.substring(21,27)
        this.certData.expireDate = validUtilDate
        this.certData.mrz = this.certData.mrz2
        //国家代码
        var countryCode = mrz2.substring(10,13)

        //识别mrz1码
        var mrz1List = RegexUtil.matchMRZ1(text, countryCode)
        console.log(mrz1List)
        if(!mrz1List || mrz1List.length==0){
          this.$message.error('照片不清晰，部分内容识别失败，请重新拍照识别')
          return
        }
        var mrz1 = mrz1List[0]
        this.certData.mrz1 = mrz1
        this.certData.type = EnumUtil.getCertType(mrz1.substring(0, 2))
        this.certData.conuntry = EnumUtil.getCountry(mrz1.substring(2, 5))
        this.certData.nationality = this.certData.conuntry
        this.certData.zhFirstName = ''
        this.certData.zhLastName = ''
        this.certData.zhName = ''
        var firstName = false
        var secondName = true
        var preNotLetter = false
        for(var x=5;x<mrz1.length;x++){
          var c = mrz1[x]
          if(!RegexUtil.isLetter(c)){
            if(secondName) {
              firstName = false
              secondName = false
            }else if(firstName){
              if(!preNotLetter){
                this.certData.zhFirstName = this.certData.zhFirstName + ' '
              }
              //break
            }
            preNotLetter = true
            continue
          }
          preNotLetter = false
          if(secondName){
            this.certData.zhLastName = this.certData.zhLastName + c
          }else{
            firstName = true
            this.certData.zhFirstName = this.certData.zhFirstName + c
          }
        }
        this.certData.zhName = this.certData.zhLastName + ' ' + this.certData.zhFirstName
        this.certData.mrz = this.certData.mrz1 + '\n' + this.certData.mrz2
      },
      readCertByUmi(file, callback){
        var thiz = this
        FileUtil.imageToBase64simple(file, function (base64) {
          var params = {
            base64: base64,
            options: {
              "ocr.language": "models/config_chinese.txt",
              "ocr.maxSideLen": 960,
              "ocr.cls": false,
              "tbpu.parser": "MergeLine",
            }
          }
          thiz.loading = true
          axios.post('http://127.0.0.1:1224/api/ocr', params).then(function (res) {
            thiz.loading = false
            var resData = res.data || {}
            if(resData.code !== 100){
              thiz.$message.error('识别失败')
              return
            }
            var datas = resData.data || []
            var list = []
            for(var i=0;i<datas.length;i++){
              var data = datas[i]
              var text = data.text
              var ds = text.split(' ')
              for(var j=0;j<ds.length;j++){
                list.push(ds[j])
              }
            }
            console.log('识别数据:',datas)
            for(var i=0;i<list.length;i++){
              //var data = datas[i]
              var text = list[i]
              if(text.startsWith('姓')){
                //text = datas[i+1].text
                text = list[i+1]
                var strs = thiz.parseChname(text)
                thiz.certData.chName = strs[0]
                thiz.certData.zhFamilyName = strs[1]
                thiz.certData.zhName = strs[1]
              }else if(text.startsWith('名')){
                //text = datas[i+1].text
                text = list[i+1]
                var strs = thiz.parseChname(text)
                thiz.certData.chName += strs[0]
                thiz.certData.zhFirstName = strs[1]
                thiz.certData.zhName += ' ' + strs[1]
              }else if(text.startsWith('性别') && !thiz.certData.gender){
                //text = datas[i+2].text
                text = list[i+2]
                var strs = text.split('/')
                thiz.certData.gender = strs[0]
              }else if(text.startsWith('出生地点')){
                //text = datas[i+2].text
                text = list[i+2]
                thiz.certData.birthPlace = text
              }else if(text.startsWith('出生日期') && !thiz.certData.birthday){
                //text = datas[i+2].text
                text = list[i+2]
                thiz.certData.birthday = text
              }else if(text.startsWith('签发地点')){
                //text = datas[i+2].text
                text = list[i+2]
                thiz.certData.signPlace = text
              }else if(text.startsWith('签发日期')){
                //text = datas[i+2].text
                text = list[i+2]
                thiz.certData.signDate = text
              }else if(text.startsWith('有效期至') && !thiz.certData.expireDate){
                //text = datas[i+2].text
                text = list[i+2]
                thiz.certData.expireDate = text
              }else if(text.startsWith('签发机关')){
                //text = datas[i+1].text
                text = list[i+1]
                thiz.certData.signOrg = text
              }else if(text.startsWith('PO')){
                console.log(text,text.substring(2, 5))
                thiz.certData.type = EnumUtil.getCertType(text.substring(0, 2))
                thiz.certData.conuntry = EnumUtil.getCountry(text.substring(2, 5))
                thiz.certData.nationality = thiz.certData.conuntry
                thiz.certData.mrz1 = text
                thiz.certData.mrz = thiz.certData.mrz1 + '\n' +thiz.certData.mrz2
                console.log(text,text.substring(2, 5),thiz.certData.nationality)
                thiz.certData.zhFirstName = ''
                thiz.certData.zhLastName = ''
                thiz.certData.zhName = ''
                var firstName = true
                for(var x=5;x<text.length;x++){
                  var c = text[x]
                  if(!RegexUtil.isLetter(c)){
                    firstName = false
                    continue
                  }
                  if(firstName){
                    thiz.certData.zhFirstName = thiz.certData.zhFirstName + c
                  }else{
                    thiz.certData.zhLastName = thiz.certData.zhLastName + c
                  }
                }
                thiz.certData.zhName = thiz.certData.zhFirstName + ' ' + thiz.certData.zhLastName
              }else if(RegexUtil.isMRZ2(text) && text.length==44){
                thiz.certData.mrz2 = text
                thiz.certData.mrz = thiz.certData.mrz1 + '\n' +thiz.certData.mrz2
                var date = new Date();
                var yearNum = parseInt((date.getFullYear()+'').substring(2,4))
                //提取护照号码
                var passportNum = text.substring(0,9)
                thiz.certData.certNo = passportNum
                //提取持证人生日
                var birthDate = ''
                if(parseInt(text.substring(13, 15))>yearNum){
                  birthDate = '19' + text.substring(13, 19)
                }else{
                  birthDate = '20' + text.substring(13, 19)
                }
                thiz.certData.birthday = birthDate
                //提取持证人性别
                var gender = text.substring(20,21)
                thiz.certData.gender = EnumUtil.getGender(gender)
                //提取护照有效截止期
                var validUtilDate = '20' + text.substring(21,27)
                thiz.certData.expireDate = validUtilDate
              }
              console.log(i,'--',text)
            }
            if(callback){
              callback.call(thiz)
            }
          }).catch(function (error) {
            thiz.loading = false
            thiz.$message.error(error)
          })
        })
      },
      parseChname(str){
        var ch = ''
        var zh = ''
        for(var i=0;i<str.length;i++){
          var char = str.substring(i, i+1)
          if(RegexUtil.isChinese(char)){
            ch += char
          }else{
            zh += char
          }
        }
        return [ch, zh.substring(1)]
      },
      readCertByBaidu(file, callback){
        var thiz = this
        var baiduOcrClient = this.baiduOcrClient

        FileUtil.imageToBase64(file, function (base64) {
          // 调用通用文字识别, 图片参数为本地图片
          var options = {
            language_type: 'CHN_ENG',
            detect_direction: true,
            detect_language: true,
            probability: true
          }
          thiz.loading = true
          baiduOcrClient.passport(base64, options).then(function(result) {
            thiz.loading = false
            console.log(result)
            var wordsResult = result.words_result || {}
            var mrz1 = thiz.getResultWords(wordsResult,'MRZCode1','words')
            if(mrz1){
              thiz.certData.type = EnumUtil.getCertType(mrz1.substring(0, 2))
            }
            thiz.certData.certNo = thiz.getResultWords(wordsResult,'护照号码','words')
            thiz.certData.chName = thiz.getResultWords(wordsResult,'姓名','words')
            var pinyinName = thiz.getResultWords(wordsResult,'姓名拼音','words')
            if(pinyinName) {
              var chNames = pinyinName.split(',')
              thiz.certData.zhFirstName = chNames[1]
              thiz.certData.zhFamilyName = chNames[0]
              thiz.certData.zhName = chNames[1] + ' ' + chNames[0]
            }
            var gender = thiz.getResultWords(wordsResult,'性别','words')
            if(gender) {
              thiz.certData.gender = gender.substring(0, 1)
            }
            var countryCode = thiz.getResultWords(wordsResult,'国家码','words')
            var nationality = thiz.getResultWords(wordsResult,'国籍','words')
            thiz.certData.nationality = EnumUtil.getCountry(countryCode)
            thiz.certData.birthday = thiz.getResultWords(wordsResult,'生日','words')
            thiz.certData.birthPlace = thiz.getResultWords(wordsResult,'出生地点','words')
            thiz.certData.expireDate = thiz.getResultWords(wordsResult,'有效期至','words')
            thiz.certData.country = EnumUtil.getCountry(countryCode)
            thiz.certData.signPlace = thiz.getResultWords(wordsResult,'护照签发地点','words')
            thiz.certData.signOrg = thiz.getResultWords(wordsResult,'签发机关','words')
            thiz.certData.signDate = thiz.getResultWords(wordsResult,'签发日期','words')
            thiz.certData.mrz1 = thiz.getResultWords(wordsResult,'签发日期','words')
            thiz.certData.mrz2 = thiz.getResultWords(wordsResult,'签发日期','words')
            thiz.certData.mrz = thiz.certData.mrz1 + '\n' +thiz.certData.mrz2
            if(callback){
              callback.call(thiz)
            }
          }).catch(function(err) {
            thiz.loading = false
            // 如果发生网络错误
            console.log(err)
            thiz.$message.error(err.error_msg)
          })
        })
      },
      getResultWords(data, key1, key2){
        if(!data[key1]){
          return
        }
        return data[key1][key2]
      },
      readCertByTencent(file, callback){
        var thiz = this
        var ocrClient = this.tencentOcrClient
        this.loading = true
        FileUtil.imageToBase64(file, function (base64) {
          const params = {
            "ImageBase64": base64,
            "Type": "CN"
          }
          ocrClient.PassportOCR(params).then(
                  (data) => {
                    thiz.loading = false
                    if(data.CodeSet){
                      thiz.certData.type = EnumUtil.getCertType(data.CodeSet.substring(0, 2))
                    }
                    thiz.certData.certNo = data.PassportNo
                    thiz.certData.chName = data.Name
                    thiz.certData.zhFirstName = data.FirstName
                    thiz.certData.zhFamilyName = data.FamilyName
                    thiz.certData.zhName = data.FirstName + ' ' + data.FamilyName
                    thiz.certData.gender = EnumUtil.getGender(data.Sex)
                    thiz.certData.nationality = EnumUtil.getCountry(data.Nationality)
                    thiz.certData.birthday = data.BirthDate
                    thiz.certData.birthPlace = data.BirthPlace
                    thiz.certData.expireDate = data.ExpiryDate
                    thiz.certData.country = EnumUtil.getCountry(data.Country)
                    thiz.certData.signPlace = data.IssuePlace
                    thiz.certData.signDate = data.IssueDate
                    thiz.certData.signature = data.Signature
                    thiz.certData.mrz1 = data.Signature
                    thiz.certData.mrz2 = data.Signature
                    thiz.certData.mrz = thiz.certData.mrz1 + '\n' +thiz.certData.mrz2
                    if(callback){
                      callback.call(thiz)
                    }
                  },
                  (err) => {
                    thiz.loading = false
                    console.error("error", err);
                    thiz.$message.error(err)
                  }
          );
        })
      },
      exist(){
        this.$confirm('确定退出程序?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          remote.getCurrentWindow().close()
        }).catch(() => {

        })
      },
      takePhoto(){
        var deskew = '0'
        var deskewval = ''
        if(this.cutEdgeVal || this.cutEdgeVal===0){
          deskew = '1'
          deskewval = this.cutEdgeVal
        }
        console.log(deskew, deskewval, this.cutEdgeVal)
        let params = {
          "filepath": this.getImageFilePath(),
          //"cutpage": "0",
          "camidx": this.vedioIndex,
          // 色彩模式，图片保存本地时调用。0：彩色 1：灰色 2：黑白 3：白纸印章 4：去背景色(普通文件) 5:去背景色(身份证)
          "ColorMode": "0",
          // 图片质量，图片保存本地调用。0:默认质量；1:高质量；2:较高质量；3:中质量；4:较低质量；5:低质量
          "quality": "3",
          deskew: deskew,
          deskewval: deskewval
        }
        EloamInterface.view_scan(params,function (succ, file) {
          this.loading = false
          if(!succ){
            this.$message({
              message: '请检查摄像头是否打开',
              type: 'warning'
            })
            return
          }
          this.certData.certImages.push({
            filePath: file,
            checked: false
          })
        }, this)
      },
      delImages(index){
        var thiz = this
        this.$confirm('确认删除图片?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          for(var i=thiz.certData.certImages.length-1;i>=0;i--){
            if(thiz.certData.certImages[i].checked){
              thiz.certData.certImages.splice(i, 1)
              thiz.imageCheckCount --
            }
          }
        })
      },
      readCertByReader(mrz){
        this.reader.mrz = mrz
        WebSocketUtil.sendMessage(this.reader, function (data) {
          console.log('接收服务端消息',data)
          if(data.code!=0){
            console.log('读取读卡器数据失败')
            return
          }
          if(data.faceBase64){
            var filePath = this.getImageFilePath('photo.jpg')
            FileUtil.base64ToFile(data.faceBase64, filePath)
            this.certData.certPhoto = filePath
          }
          this.certData.certNo = data.zjhm
          //this.certData.birthday = data.csrq
          this.certData.expireDate = data.yxqz
        }, this)
      },
      /*start(){
        this.readCertByReader("E006666693CHN8105185M2206194MDKLLELKNDMCA932")
      },*/
      saveImage(){
        var thiz = this
        dialog.showOpenDialog({
          //对话框标题
          title:'选择路径',
          //设置选择的文件名称
          //defaultPath:'1.jpg',
          //过滤文件类型
          /*filters:[
            { name: 'Images', extensions: ['jpg', 'png'] }
          ],*/
          properties: ['openDirectory']
        },result=>{
          //图片选中后将回调此方法
          //返回的是一个对象
          console.log(result)
          //保存文件路径
          var path = result[0]
          SystemConfig.saveSystemConfigType('baseImgPath', path + '\\')
          /*//保存头像
          var photo = thiz.certData.certPhoto
          var fileList = []
          if(photo){
            fileList.push(photo)
          }
          for(var n=0;n<thiz.certData.certImages.length;n++){
            fileList.push(thiz.certData.certImages[n].filePath)
          }
          //fileList = fileList.concat(thiz.certData.certImages)
          thiz.loading = true
          thiz.saveCertFile(fileList, 0, path)*/
        })
      },
      saveCertFile(fileList, i, path){
        var len = fileList.length
        console.log('save file:',len,i,path)
        if(len==0){
          this.loading = false
          return
        }
        if(len==i){
          this.loading = false
          this.$message({
            message: '保存成功',
            type: 'success'
          })
          return
        }
        var file = fileList[i]
        this.copyCertFile(file, path, function (error, dest) {
          if(error){
            this.loading = false
            this.$message.error('图片保存失败：'+error)
            return
          }
          this.saveCertFile(fileList, i + 1, path)
        })
      },
      copyCertFile(file, path, callback){
        var thiz = this
        var files = file.split('\\')
        console.log(files)
        var destFile = path + '\\' + files[files.length - 1]
        FileSystem.copyFile(file, destFile, function (error, dest) {
          console.log(error, dest)
          callback.call(thiz, error, dest)
        })
      },
      readElecCert(){
        var mrz = this.certData.mrz2
        if(!mrz){
          this.$message.error('缺少证件MRZ信息')
          return
        }
        this.reader.mrz = mrz
        this.loading = true
        WebSocketUtil.sendMessage(this.reader, function (data) {
          console.log('接收服务端消息',data)
          this.loading = false
          if(data.code!=0){
            console.log('读取读卡器数据失败')
            this.$message.error(data.message || '读取电子信息失败')
            return
          }
          if(data.faceBase64){
            var filePath = this.getImageFilePath('photo.jpg')
            FileUtil.base64ToFile(data.faceBase64, filePath)
            this.certData.certPhoto = filePath
          }
          this.certData.certNo = data.zjhm
          //this.certData.birthday = data.csrq
          this.certData.expireDate = data.yxqz
        }, this)
      },
      async autoTakePhoto(){
        var autoPhoto = !this.autoPhoto
        console.log('this.autoPhoto', autoPhoto)
        if(autoPhoto){
          this.autoPhoto = true
          var path = this.getImageFilePathOnly()
          this.autoScan(path)
        }else {
          this.closeAutoScan()
          this.autoPhoto = false
        }
      },
      // 自动拍照
      async autoScan(filepath) {
        //this.parseEloamMrz('EF09777771CHN9108116M2901282M0MEMGLN<<<<A914')
        //return
        let result = await axios.post(
                "http://127.0.0.1:38088/video=movedetec",
                {
                  movedetecflag: '1',           // 开启自动拍照
                  listpath: filepath,   // 图片保存目录
                  filepath: 'LT',                // 图片名称前缀
                  bAutoAdjust: 1,
                  ColorMode: 0, // 色彩模式，图片保存本地时调用。0：彩色 1：灰色 2：黑白 3：白纸印章 4：去背景色(普通文件) 5:去背景色(身份证)
                  deskew: 0,      // 纠偏（主头有效），参数：0:不纠偏；1:纠偏
                  deskewval: 10,       // 纠偏像素值：正常给0，正数时多裁，负数时少裁
                }
        )
        if (result.data.code === "0") {
          // console.log(result.data.data)
          if (result.data.data) {
            //this.photoList.push("data:image/png;base64," + result.data.data)
            var base64 = result.data.data
            var filePath = this.getImageFilePath()
            FileUtil.base64ToFile(base64, filePath)
            this.certData.certImages.push({
              filePath: filePath,
              checked: false
            })
            this.autoScan()
          }
        } else {
          console.log('auto photo result:',result)
          this.autoPhoto = false
          this.$message.error('开启自动拍照失败')
        }
      },
      closeAutoScan() {
        axios.post("http://127.0.0.1:38088/video=movedetec", {
          "movedetecflag": "0"
        })
      },
      autoTakePicture(params){
        if(!this.autoPhoto){
          return
        }
        EloamInterface.movedetec(params, function (succ, data) {
          console.log('content', succ, data)
          if(!this.autoPhoto){
            return
          }
          if(data.code=='1'){
            this.autoPhoto = false
            return
          }
          if(data.code!='0') {
            this.$message.error('设置自动拍照失败:' + data.message)
            this.autoPhoto = false
            return
          }
          var base64 = data.data
          if(!base64){
            return
          }
          var filePath = this.getImageFilePath()
          FileUtil.base64ToFile(base64, filePath)
          this.certData.certImages.push({
            filePath: filePath,
            checked: false
          })
          this.autoTakePicture(params)
        }, this)
      },
      openCheckEdge(){
        var params = {
          camidx: this.vedioIndex,
          open: this.checkEdge?'1':'0'
        }
        EloamInterface.cameradeskew(params,function (succ) {
          console.log('cameradeskew', succ)
        },this)
      },
      checkCertImage(item){
        console.log(item.checked)
        var n = item.checked?1:-1
        this.imageCheckCount = this.imageCheckCount + n
      },
      reconnectDevice(){
        var machineId = CommonUtil.getMachineId();
        console.log('machineId', machineId)
      },
      deviceInfo(){
        this.machineInfo = CommonUtil.getMachineInfo()
        this.showDeviceInfo = true
      },
      opDev(){
        console.log('opDev')
        //ipcRenderer.send('open-devtools')
        remote.getCurrentWebContents().openDevTools()
      },
      rotation90(){
        var params = {
          camidx: this.vedioIndex, // 摄像头，0:主头；1:副头
          rotate: "90"
        }
        EloamInterface.rotation(params, function (succ) {
          if(succ){
            this.$message({
              message: '选择成功',
              type: 'success'
            })
          }else{
            this.$message.error('旋转镜头失败')
          }
        }, this)
      }
    }
  }
</script>

<style>
  @import url('https://fonts.googleapis.com/css?family=Source+Sans+Pro');

  * {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
  }

  body { font-family: 'Source Sans Pro', sans-serif; }

  #wrapper {
    padding: 0 10px;
  }

  .read-button .el-form-item__content{
    text-align: center;
  }
  .image-slot{
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 14px;
    color: #c0c4cc;
    vertical-align: middle;
    background: #f5f7fa;
    height: 100%;
  }
  .config-cls .el-card__body{
    padding: 0px 10px 10px;
  }
  .btn-block{
    padding-top: 5px;
  }
  .btn-block .el-button{
    padding: 10px 6px;
  }
  .main-block .el-card__body{
    padding: 10px 10px 0px;
  }
  .images-card .el-card__body{
    padding: 0px 0px;
  }
  .btn-select{
    background: #409eff !important;
    border-color: #409eff !important;
    color: #fff !important;
  }
  .image-container{
    overflow-y: auto;
  }
  .icon-btn{
    cursor: pointer;
    border: 1px solid #fff;
  }
  .icon-btn:hover{
    border: 1px solid #ccc;
  }
  .center-flex {
    display: flex;
    justify-content: center; /* 水平居中 */
    align-items: center; /* 垂直居中 */
    height: 100vh; /* 使div的高度为视口高度 */
  }
</style>
